# 发送带参数请求
# 请求参数的形式：字典    kw = {'wd':'长城'}
# 请求参数的用法   requests.get(url,params=kw)
"""
https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=Python

查询字符串参数的格式：
    以问号开始
    key = value
    多个参数 每个参数之间使用 & 进行连接

经验： 参数  必传参数  非必传参数    后续抓包 拿到的地址中的参数特别多，尝试进行删除某些参数

https://www.baidu.com/s?wd=Python

发送带参数的请求:
1.  直接请求完整的路径 （参数比较少的时候）
2.  在发送请求的时候 requests.get(url,headers,params={})
    params 接收的是一个字典类型的数据。
    wd=Python     等号前面的内容作为字典的key  等号右边的内容作为字典的value
"""

# 两种方式：发送带参数的请求
# 1.对https://www.baidu.com/s?wd=python发起请求可以使用requests.get(url, params=kw)的方式
import requests

# 利用params参数发送带参数的请求
# 这是目标url
# url = "https://www.baidu.com/s?wd=Python"
# 最后有没有问号结果都一样
url = "https://www.baidu.com/s?"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36",
    "Cookie": "BIDUPSID=7c0e881398940863b9db5e9b89ffb894; PSTM=1592276581; H_PS_PSSID=1424_31326_21092_31254_31765_32046_30824_26350_22160; BAIDUID=7c0e881398940863b9db5e9b89ffb894:FG=1; BD_UPN=12314753; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; delPer=0; BD_CK_SAM=1; PSINO=1; COOKIE_SESSION=20_0_0_2_0_2_0_0_0_2_0_0_0_0_0_0_0_0_1592281095%7C3%230_0_1592281095%7C1; H_PS_645EC=e100RR4O5qf00cQAILH8V9XnWSk1Uu%2FW5FHSVQSEhqRu7m7mIFuLii92mjA; BD_HOME=1"
}

# 构造参数的字典
params = {"wd": "Python"}

# 带上请求参数发起请求，获取响应
# 当有多个请求参数时，requests接收的params参数为多个键值对的字典，比如 '?wd=python&a=c'-->{'wd': 'python', 'a': 'c'}
# response = requests.get(url, headers=headers, params={"wd": "Python"})
response = requests.get(url, headers=headers, params=params)
print(response.content.decode())

with open("baidu(params1).html", "w", encoding="utf-8") as f:
    f.write(response.content.decode())


# 2.直接对https://www.baidu.com/s?wd=python完整的url直接发送请求，不使用params参数
import requests


headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36",
    "Cookie": "BIDUPSID=7c0e881398940863b9db5e9b89ffb894; PSTM=1592276581; H_PS_PSSID=1424_31326_21092_31254_31765_32046_30824_26350_22160; BAIDUID=7c0e881398940863b9db5e9b89ffb894:FG=1; BD_UPN=12314753; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; delPer=0; BD_CK_SAM=1; PSINO=1; COOKIE_SESSION=20_0_0_2_0_2_0_0_0_2_0_0_0_0_0_0_0_0_1592281095%7C3%230_0_1592281095%7C1; H_PS_645EC=e100RR4O5qf00cQAILH8V9XnWSk1Uu%2FW5FHSVQSEhqRu7m7mIFuLii92mjA; BD_HOME=1"
}

# 直接发送带参数的url请求
url = 'https://www.baidu.com/s?wd=python'

# url中包含了请求参数，所以此时无需params
response = requests.get(url, headers=headers)

with open('baidu(params2).html', 'w', encoding='utf-8') as f:
    f.write(response.content.decode())
